<template>
  <div class="learning-page">
    <!-- 顶部导航栏 -->
    <div class="top-navbar">
      <div class="navbar-container">
        <div class="navbar-left">
          <router-link to="/" class="logo-link">
            <svg viewBox="0 0 24 24" width="32" height="32" fill="currentColor">
              <path d="M12 2L2 7v10c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V7l-10-5z"/>
            </svg>
            <span class="logo">M-Learning</span>
          </router-link>
        </div>
        
        <!-- 中间导航菜单 -->
        <div class="navbar-center">
          <router-link to="/" class="nav-link">首页</router-link>
          <a href="#" class="nav-link active">在线学习</a>
          <router-link to="/problems" class="nav-link">在线答题</router-link>
          <router-link to="/discussion" class="nav-link">学习社区</router-link>
          <router-link to="/profile" class="nav-link">个人中心</router-link>
        </div>
        
        <!-- 右侧用户信息 -->
        <div class="navbar-right">
          <div class="user-info" @click="toggleUserMenu">
            <img :src="getAvatarUrl(userInfo.avatar)" class="user-avatar" alt="头像" />
            <span class="username">{{ userInfo.username }}</span>
            <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" class="dropdown-icon">
              <path d="M7 10l5 5 5-5z"/>
            </svg>
          </div>
          
          <!-- 用户下拉菜单 -->
          <div v-if="showUserMenu" class="user-dropdown">
            <router-link to="/profile" class="dropdown-item">个人资料</router-link>
            <router-link to="/my-learning" class="dropdown-item">我的学习</router-link>
            <router-link to="/my-posts" class="dropdown-item">我的帖子</router-link>
            <div v-if="userStore.isAdmin" class="dropdown-divider"></div>
            <router-link v-if="userStore.isAdmin" to="/learning/manage" class="dropdown-item">
              <span style="color: #ff6b6b; font-weight: 600;">📹 课程管理</span>
            </router-link>
            <div class="dropdown-divider"></div>
            <a @click="handleLogout" class="dropdown-item">退出登录</a>
          </div>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <div class="content-container">
        <!-- 左侧分类筛选 -->
        <aside class="sidebar">
          <div class="filter-section">
            <h3>课程分类</h3>
            <div class="category-list">
              <div 
                v-for="category in categories" 
                :key="category.id"
                :class="['category-item', { active: selectedCategory === category.id }]"
                @click="selectCategory(category.id)"
              >
                <span class="category-icon">{{ category.icon }}</span>
                <span class="category-name">{{ category.name }}</span>
                <span class="category-count">({{ category.count }})</span>
              </div>
            </div>
          </div>
          
          <div class="filter-section">
            <h3>难度等级</h3>
            <div class="difficulty-list">
              <div 
                v-for="level in difficulties" 
                :key="level.value"
                :class="['difficulty-item', { active: selectedDifficulty === level.value }]"
                @click="selectDifficulty(level.value)"
              >
                <span :class="['difficulty-badge', level.value]">{{ level.label }}</span>
                <span class="difficulty-count">({{ level.count }})</span>
              </div>
            </div>
          </div>
        </aside>

        <!-- 右侧课程列表 -->
        <main class="course-list-area">
          <!-- 顶部标题栏 -->
          <div class="list-header">
            <div class="header-left">
              <h2>{{ currentCategoryName }}</h2>
              <router-link v-if="userStore.isAdmin" to="/learning/manage" class="manage-btn">
                📹 课程管理
              </router-link>
            </div>
            <div class="sort-options">
              <button 
                v-for="option in sortOptions" 
                :key="option.value"
                :class="['sort-btn', { active: sortBy === option.value }]"
                @click="changeSortBy(option.value)"
              >
                {{ option.label }}
              </button>
            </div>
          </div>

          <!-- 课程卡片列表 -->
          <div v-if="loading" class="loading-state">
            <div class="loading-spinner"></div>
            <p>加载中...</p>
          </div>

          <div v-else-if="courses.length === 0" class="empty-state">
            <svg viewBox="0 0 24 24" width="64" height="64" fill="currentColor" opacity="0.3">
              <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/>
            </svg>
            <p>暂无课程</p>
          </div>

          <div v-else class="course-grid">
            <div 
              v-for="course in courses" 
              :key="course.id"
              class="course-card"
              @click="goToCourseDetail(course.id)"
            >
              <div class="course-cover">
                <img :src="course.cover || getDefaultCover()" :alt="course.title" />
                <div class="course-overlay">
                  <div class="video-count">
                    <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                      <path d="M8 5v14l11-7z"/>
                    </svg>
                    {{ course.videoCount }} 个视频
                  </div>
                </div>
              </div>
              
              <div class="course-info">
                <h3 class="course-title">{{ course.title }}</h3>
                <p class="course-desc">{{ course.description }}</p>
                
                <div class="course-meta">
                  <span :class="['difficulty-tag', course.difficulty]">
                    {{ getDifficultyText(course.difficulty) }}
                  </span>
                  <span class="course-students">
                    <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor">
                      <path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/>
                    </svg>
                    {{ course.studentCount }} 人学习
                  </span>
                </div>
                
                <div class="course-footer">
                  <div class="course-instructor">
                    <img :src="getAvatarUrl(course.instructor.avatar)" :alt="course.instructor.name" />
                    <span>{{ course.instructor.name }}</span>
                  </div>
                  <div v-if="course.progress > 0" class="course-progress">
                    <div class="progress-bar">
                      <div class="progress-fill" :style="{ width: course.progress + '%' }"></div>
                    </div>
                    <span class="progress-text">{{ course.progress }}%</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div v-if="totalPages > 1" class="pagination">
            <button 
              class="page-btn"
              :disabled="currentPage === 1"
              @click="changePage(currentPage - 1)"
            >
              上一页
            </button>
            <span class="page-info">第 {{ currentPage }} / {{ totalPages }} 页</span>
            <button 
              class="page-btn"
              :disabled="currentPage === totalPages"
              @click="changePage(currentPage + 1)"
            >
              下一页
            </button>
          </div>
        </main>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { getCourseCategories, getCourseList } from '../api/learning'
import { getAvatarUrl } from '../utils/url'
import { closeWebSocket } from '../utils/websocket'

const router = useRouter()
const userStore = useUserStore()

const userInfo = computed(() => userStore.userInfo)
const showUserMenu = ref(false)

// 筛选条件
const selectedCategory = ref(null)
const selectedDifficulty = ref(null)
const sortBy = ref('latest')

// 数据
const categories = ref([])
const courses = ref([])
const loading = ref(false)

// 分页
const currentPage = ref(1)
const pageSize = ref(12)
const totalCourses = ref(0)

const totalPages = computed(() => Math.ceil(totalCourses.value / pageSize.value))

// 难度选项
const difficulties = ref([
  { value: null, label: '全部', count: 0 },
  { value: 'beginner', label: '入门', count: 0 },
  { value: 'intermediate', label: '进阶', count: 0 },
  { value: 'advanced', label: '高级', count: 0 }
])

// 排序选项
const sortOptions = [
  { value: 'latest', label: '最新发布' },
  { value: 'popular', label: '最多学习' },
  { value: 'recommended', label: '推荐' }
]

const currentCategoryName = computed(() => {
  if (!selectedCategory.value) return '全部课程'
  const category = categories.value.find(c => c.id === selectedCategory.value)
  return category ? category.name : '全部课程'
})

function toggleUserMenu() {
  showUserMenu.value = !showUserMenu.value
}

function handleLogout() {
  closeWebSocket()
  userStore.logout()
  router.push('/login')
}

function selectCategory(categoryId) {
  selectedCategory.value = categoryId === selectedCategory.value ? null : categoryId
  currentPage.value = 1
  loadCourses()
}

function selectDifficulty(difficulty) {
  selectedDifficulty.value = difficulty === selectedDifficulty.value ? null : difficulty
  currentPage.value = 1
  loadCourses()
}

function changeSortBy(value) {
  sortBy.value = value
  loadCourses()
}

function changePage(page) {
  currentPage.value = page
  loadCourses()
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

function getDifficultyText(difficulty) {
  const map = {
    beginner: '入门',
    intermediate: '进阶',
    advanced: '高级'
  }
  return map[difficulty] || difficulty
}

function getDefaultCover() {
  return 'https://via.placeholder.com/400x225?text=Course+Cover'
}

function goToCourseDetail(courseId) {
  router.push(`/learning/course/${courseId}`)
}

async function loadCategories() {
  try {
    const res = await getCourseCategories()
    console.log('✅ 分类数据:', res)
    if (res.code === 200) {
      categories.value = [
        { id: null, name: '全部分类', icon: '📚', count: res.data.total || 0 },
        ...res.data.categories
      ]
    }
  } catch (error) {
    console.error('❌ 加载分类失败:', error)
  }
}

async function loadCourses() {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      categoryId: selectedCategory.value,
      difficulty: selectedDifficulty.value,
      sortBy: sortBy.value
    }
    
    console.log('📊 查询参数:', params)
    const res = await getCourseList(params)
    console.log('✅ 课程数据:', res)
    
    if (res.code === 200) {
      courses.value = res.data.list
      totalCourses.value = res.data.total
    }
  } catch (error) {
    console.error('❌ 加载课程失败:', error)
    courses.value = []
    totalCourses.value = 0
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadCategories()
  loadCourses()
})
</script>

<style scoped lang="scss">
.learning-page {
  min-height: 100vh;
  background: #f8f9fa;
}

// 顶部导航栏样式（复用之前的）
.top-navbar {
  background: white;
  border-bottom: 1px solid #e1e4e8;
  position: sticky;
  top: 0;
  z-index: 100;
  
  .navbar-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 24px;
    height: 64px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  
  .navbar-left {
    .logo-link {
      display: flex;
      align-items: center;
      gap: 8px;
      text-decoration: none;
      color: #667eea;
      font-weight: 600;
      font-size: 20px;
    }
  }
  
  .navbar-center {
    display: flex;
    gap: 32px;
    
    .nav-link {
      color: #586069;
      text-decoration: none;
      font-size: 15px;
      transition: color 0.2s;
      
      &:hover, &.active {
        color: #667eea;
      }
    }
  }
  
  .navbar-right {
    position: relative;
    
    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;
      cursor: pointer;
      padding: 8px 12px;
      border-radius: 6px;
      transition: background 0.2s;
      
      &:hover {
        background: #f6f8fa;
      }
      
      .user-avatar {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        object-fit: cover;
      }
      
      .username {
        font-size: 14px;
        color: #24292f;
      }
    }
    
    .user-dropdown {
      position: absolute;
      top: 100%;
      right: 0;
      margin-top: 8px;
      background: white;
      border: 1px solid #d0d7de;
      border-radius: 6px;
      box-shadow: 0 8px 24px rgba(140, 149, 159, 0.2);
      min-width: 180px;
      padding: 8px 0;
      z-index: 101;
      
      .dropdown-item {
        display: block;
        padding: 8px 16px;
        color: #24292f;
        text-decoration: none;
        font-size: 14px;
        cursor: pointer;
        transition: background 0.2s;
        
        &:hover {
          background: #f6f8fa;
        }
      }
      
      .dropdown-divider {
        height: 1px;
        background: #e1e4e8;
        margin: 8px 0;
      }
    }
  }
}

// 主内容区
.main-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 32px 24px;
  
  .content-container {
    display: grid;
    grid-template-columns: 240px 1fr;
    gap: 32px;
  }
}

// 左侧筛选栏
.sidebar {
  .filter-section {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    
    h3 {
      font-size: 16px;
      color: #24292f;
      margin: 0 0 16px 0;
      font-weight: 600;
    }
    
    .category-list, .difficulty-list {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }
    
    .category-item, .difficulty-item {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 10px 12px;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover {
        background: #f6f8fa;
      }
      
      &.active {
        background: #f0f6ff;
        color: #667eea;
        font-weight: 500;
      }
      
      .category-icon {
        font-size: 18px;
      }
      
      .category-name, .difficulty-badge {
        flex: 1;
        font-size: 14px;
      }
      
      .category-count, .difficulty-count {
        font-size: 12px;
        color: #8c959f;
      }
    }
    
    .difficulty-badge {
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      font-weight: 500;
      
      &.beginner {
        background: #dff6dd;
        color: #1a7f37;
      }
      
      &.intermediate {
        background: #fff8c5;
        color: #9a6700;
      }
      
      &.advanced {
        background: #ffebe9;
        color: #cf222e;
      }
    }
  }
}

// 右侧课程列表
.course-list-area {
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;
    }
    
    h2 {
      font-size: 24px;
      color: #24292f;
      margin: 0;
    }
    
    .manage-btn {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      padding: 8px 16px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      text-decoration: none;
      border-radius: 6px;
      font-size: 14px;
      font-weight: 600;
      transition: all 0.3s;
      box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
      }
    }
    
    .sort-options {
      display: flex;
      gap: 8px;
      
      .sort-btn {
        padding: 8px 16px;
        background: white;
        border: 1px solid #d0d7de;
        border-radius: 6px;
        font-size: 14px;
        color: #57606a;
        cursor: pointer;
        transition: all 0.2s;
        
        &:hover {
          border-color: #667eea;
          color: #667eea;
        }
        
        &.active {
          background: #667eea;
          border-color: #667eea;
          color: white;
        }
      }
    }
  }
  
  .loading-state, .empty-state {
    text-align: center;
    padding: 60px 20px;
    background: white;
    border-radius: 8px;
    
    .loading-spinner {
      width: 40px;
      height: 40px;
      margin: 0 auto 16px;
      border: 3px solid #f3f3f3;
      border-top: 3px solid #667eea;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }
    
    p {
      color: #8c959f;
      font-size: 14px;
      margin: 0;
    }
  }
  
  .course-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 24px;
    margin-bottom: 32px;
  }
  
  .course-card {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    
    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
    }
    
    .course-cover {
      position: relative;
      width: 100%;
      padding-top: 56.25%; // 16:9
      overflow: hidden;
      
      img {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .course-overlay {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 12px;
        background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
        
        .video-count {
          display: flex;
          align-items: center;
          gap: 4px;
          color: white;
          font-size: 13px;
        }
      }
    }
    
    .course-info {
      padding: 16px;
      
      .course-title {
        font-size: 16px;
        font-weight: 600;
        color: #24292f;
        margin: 0 0 8px 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .course-desc {
        font-size: 13px;
        color: #57606a;
        margin: 0 0 12px 0;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        line-height: 1.5;
        min-height: 39px;
      }
      
      .course-meta {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 12px;
        padding-bottom: 12px;
        border-bottom: 1px solid #e1e4e8;
        
        .difficulty-tag {
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 12px;
          font-weight: 500;
          
          &.beginner {
            background: #dff6dd;
            color: #1a7f37;
          }
          
          &.intermediate {
            background: #fff8c5;
            color: #9a6700;
          }
          
          &.advanced {
            background: #ffebe9;
            color: #cf222e;
          }
        }
        
        .course-students {
          display: flex;
          align-items: center;
          gap: 4px;
          font-size: 12px;
          color: #8c959f;
        }
      }
      
      .course-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .course-instructor {
          display: flex;
          align-items: center;
          gap: 8px;
          
          img {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            object-fit: cover;
          }
          
          span {
            font-size: 13px;
            color: #57606a;
          }
        }
        
        .course-progress {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .progress-bar {
            width: 60px;
            height: 4px;
            background: #e1e4e8;
            border-radius: 2px;
            overflow: hidden;
            
            .progress-fill {
              height: 100%;
              background: #667eea;
              transition: width 0.3s;
            }
          }
          
          .progress-text {
            font-size: 12px;
            color: #667eea;
            font-weight: 500;
          }
        }
      }
    }
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 16px;
    padding: 24px 0;
    
    .page-btn {
      padding: 8px 16px;
      background: white;
      border: 1px solid #d0d7de;
      border-radius: 6px;
      font-size: 14px;
      color: #24292f;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover:not(:disabled) {
        border-color: #667eea;
        color: #667eea;
      }
      
      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }
    
    .page-info {
      font-size: 14px;
      color: #57606a;
    }
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>

